import { ElNotification } from 'element-plus'
import cloneDeep from 'lodash/cloneDeep'

export function deepClone(obj) {
  return cloneDeep(obj)
  // return JSON.parse(JSON.stringify(obj))
}

export function successNotify(msg = '操作成功') {
  ElNotification({
    title: 'Success',
    message: msg,
    type: 'success',
  })
}

export function failedNotify(msg = '操作失败') {
  ElNotification({
    title: 'Error',
    message: msg,
    type: 'error',
  })
}

export function intToBit(val) {
  let decimalNumber = parseInt(val)
  let binaryNumber = decimalNumber.toString(2).padStart(8, '0')
  console.log(binaryNumber);
  return binaryNumber
}

export function floatToBytes32(num) {
  
  var buffer = new ArrayBuffer(4)
  let view = new DataView(buffer)
  // 将浮点数转换为32位大端字节序
  view.setFloat32(0, num, false)

  // 从TypedArray中获取字节序列
  let byteArray = new Uint8Array(buffer)
  // let byteArr = []
  // byteArray.forEach(byte => {
  //     byteArr.push(byte)
  // })
  return Array.from(byteArray)
}

export function signedToBytes16(num) {
  var buffer = new ArrayBuffer(2)
  let view = new DataView(buffer)

  view.setInt16(0, num, false)
  let byteArray = new Uint8Array(buffer)
  return Array.from(byteArray)
}

export function evalFunc(formulaStr, x) {
  const createFormulaFunction = (formulaString) => {
    return new Function('x', `return ${formulaString}`);
  };

  // 使用示例
  const formulaString = formulaStr;
  const formulaFunction = createFormulaFunction(formulaString);

  // 调用计算公式并计算结果
  const result = formulaFunction(x);
  return result
}

export function blendTwoColors(color1, color2) {
  // 将颜色转换为RGB格式
  function hexToRgb(hex) {
      return {
          r: parseInt(hex?.substring(1, 3), 16),
          g: parseInt(hex?.substring(3, 5), 16),
          b: parseInt(hex?.substring(5, 7), 16)
      };
  }

  // 将RGB颜色转换为16进制格式
  function rgbToHex(rgb) {
      return '#' + ((1 << 24) + (rgb.r << 16) + (rgb.g << 8) + rgb.b).toString(16).slice(1);
  }

  var rgb1 = hexToRgb(color1);
  var rgb2 = hexToRgb(color2);

  var blendedColor = {
      r: Math.round((rgb1.r + rgb2.r) / 2),
      g: Math.round((rgb1.g + rgb2.g) / 2),
      b: Math.round((rgb1.b + rgb2.b) / 2)
  };

  return rgbToHex(blendedColor);
}

export function hashFunction(num, maxSize) {
  return (num % maxSize) % 11; // 取模操作确保哈希值在0到10之间
}

export const downloadFile = (response) => {
  const getFileNameFromResponseHeaders = (response) => {
    const contentDisposition = response.headers['content-disposition']
    const filenameMatch = contentDisposition.match(/filename=(.+)/)
    return filenameMatch ? filenameMatch[1] : 'export4.xlsx'
  }

  const url = window.URL.createObjectURL(new Blob([response.data]))
  const link = document.createElement('a')
  link.href = url
  const filename = getFileNameFromResponseHeaders(response)
  link.setAttribute('download', filename)
  document.body.appendChild(link)
  link.click()
  window.URL.revokeObjectURL(url)
}

export const tranlateBytes = (obj) => {
  const base64String = obj['parambytes']  
  const rawData = atob(base64String);  
  const outputArray = new Uint8Array(rawData.length);  
  let pArr = []
  for (let i = 0; i < rawData.length; ++i) {  
      let byte = rawData.charCodeAt(i);  
      outputArray[i] = byte
      pArr[i] = '0x' + ( byte.toString(16).padStart(2, '0') ).toUpperCase()
  } 
  return pArr.join(", ");  
}

export const isFloat= (value) => {
  return typeof value === 'number' && !Number.isInteger(value);
}

export const fixed7Float = (val) => {
  let res = (val === '') ? '--' : val
  if( !isNaN(val) && isFloat(val) ) {
    res = parseFloat(val).toFixed(7)
  }
  return res
}

//十六进制数转换成大端字节数组
export const hexToBigEndianBytes = (hexStr, len) => {
  let hexStrV = hexStr.toLowerCase();
  if (hexStr.indexOf('0x') > -1) {
    hexStrV = hexStr.replace(/^0x/, '')
  } else {
    //处理十进制的情况
    hexStrV = parseInt(hexStr).toString(16)
    for ( let i = 0; hexStrV.length < 2 * len ; i++ ) {
      hexStrV = '0' + hexStrV
    }
  }
  const hexLen = hexStrV.length
  if (hexLen > 2 * len) {
    console.log('hex string is too long, your value will be truncated!');
    hexStrV = hexStrV.substr(hexLen - 2 * len, hexLen);
  }
  // 确保 hexStr 长度为偶数，不足时前面补0
  if (hexStrV.length % 2 !== 0) {
    hexStrV = '0' + hexStrV;
  }

  // 创建一个字节数组
  let byteArray = new Uint8Array(len);

  // 将每两个十六进制字符转换为字节
  for (let i = 0; i < hexStrV.length; i += 2) {
    byteArray[i / 2] = parseInt(hexStrV.substr(i, 2), 16)
  }

  return byteArray;
}

export const decimalToHex = (decimalNumber)  => {
  // 使用 toString(16) 方法将十进制数转换为十六进制字符串
  return decimalNumber.toString(16).toUpperCase(); // 可以用 toUpperCase() 将字母转换为大写
}

export const hexToDecimal = (decimal) => {
    const hex = decimal.toString(16);
    return (hex.length < 2 ? '0' + hex : hex).toUpperCase(); // 保持前导零并转换为大写
}
